const packageFormats = process.env.FORMATS && process.env.FORMATS.split(',');
const sourceMap = process.env.SOURCE_MAP;
const target = process.env.TARGET;


// 根据target找到要打包的目录
import path from "path";
import ts from 'rollup-plugin-typescript2';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from "@rollup/plugin-commonjs";

const packagesDir = path.resolve(__dirname, 'packages'); 
const packageDir = path.resolve(packagesDir, target);


const resolve = p => path.resolve(packageDir, p); // 以打包的目录来解析文件

const pkg = require(resolve('package.json'));
const name = path.basename(packageDir); // 拿到包名

const outputConfig = {
    'esm-bundler': {
        file: resolve(`dist/${name}.esm-bundler.js`),
        format: 'es'
    },
    'cjs': {
        file: resolve(`dist/${name}.cjs.js`),
        format: 'cjs'
    },
    'global': {
        file: resolve(`dist/${name}.global.js`),
        format: 'iife' 
    }
}

const packageConfigs = packageFormats || pkg.buildOptions.formats; // 稍后打包所有文件的时候，可能不会有packageFormats值


function createConfig(format, output) { // 返回rollup的配置文件
    output.sourcemap = sourceMap;
    output.exports = 'named'; // 表示添加了名字
    let external = []; // 外部模块, 哪些模块不需要打包
    if (format === 'global') { // 打包的名字，全局使用时
        output.name = pkg.buildOptions.name
    } else {
        external = [...Object.keys(pkg.dependencies)] // 如果是es cjs，不需要打包external
    }
    return {
        input: resolve(`src/index.ts`),
        output,
        external,
        plugins: [ // plugin 从上到下
            json(),
            ts(), // 顺序问题，先转义TS，然后再解析老版本的commonjs，然后再是node模块
            commonjs(),
            nodeResolve()
        ]
    }
}
 
// 返回数组，依次进行打包
export default packageConfigs.map((format) => {
    return createConfig(format, outputConfig[format]);
})